import { store, uuid, extend } from "@/Utils";

class TodoModel {
  public key: string;
  public todos: Array<ITodoItem>;
  public onChanges: Array<Function>;

  constructor(key: string) {
    this.key = key;
    this.todos = store(key);
    this.onChanges = [];
  }

  public subscribe(onChange: Function) {
    this.onChanges.push(onChange);
  }

  public inform() {
    store(this.key, this.todos);
    this.onChanges.forEach(function (cb) {
      cb();
    });
  }

  public addTodo(title: string) {
    this.todos = this.todos.concat({
      id: uuid(),
      title,
      completed: false,
    });

    this.inform();
  }

  public toggleAll(checked: boolean) {
    this.todos = this.todos.map(function (todo) {
      return extend({}, todo, { completed: checked });
    });

    this.inform();
  }

  public toggle(todoToToggle: ITodoItem) {
    this.todos = this.todos.map(function (todo) {
      return todo !== todoToToggle
        ? todo
        : extend({}, todo, { completed: !todo.completed });
    });

    this.inform();
  }

  public destroy(todo: ITodoItem) {
    this.todos = this.todos.filter(function (candidate) {
      return candidate !== todo;
    });

    this.inform();
  }

  public save(todoToSave: ITodoItem, text: string) {
    this.todos = this.todos.map(todo => {
      return todo !== todoToSave ? todo : extend({}, todo, {title: text})
    })

    this.inform();
  }

  public clearcompletedd() {
    this.todos = this.todos.filter(function(todo) {
      return !todo.completed
    })

    this.inform();
  }
}


const todoModel = new TodoModel('react-todos')

export default todoModel